package com.crm.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.crm.entity.Askers;
import com.crm.entity.Students;
import com.crm.service.AskersService;
import com.crm.service.StudentsService;

@RestController
public class AllotSwitchController {
	
	@Autowired
	private AskersService askersService;
	
	@Autowired
	private StudentsService studentsService;
	
	/**
	 * 设置开关
	 * @param request
	 * @param valid
	 * @return
	 */
	@PostMapping("/setAllotSwitch")
	public String setAllotSwitch(HttpServletRequest request,String valid) {
		ServletContext context = request.getServletContext();
		context.setAttribute("autoAllotAskerSwitch", valid);
		return "success";
	}
	
	/**
	 * 查询开关（查询是否是自动分配咨询师）
	 * @param request
	 * @return
	 */
	@GetMapping("/getAllotSwitch")
	public Map<String, Object> getAllotSwitch(HttpServletRequest request) {
		ServletContext context = request.getServletContext();//从上下文应用域里取开关数据
		String isAuto = (String) context.getAttribute("autoAllotAskerSwitch");
		//第一次读的时候给一个默认值ON
		if (isAuto == null || isAuto.equals("")) {
			isAuto = "on";
		}
		//拼接表数据
		List<Map<String, Object>> list = new ArrayList<>();
		Map<String, Object> kgmap = new HashMap<>();
		kgmap.put("isAuto", isAuto);
		list.add(kgmap);
		//返回结果
		Map<String, Object> map = new HashMap<>();
		map.put("code", "0");
		map.put("msg", "success");
		map.put("count", 1);
		map.put("data", list);
		
		return map;
	}
	
	
	@RequestMapping("/selectAskers")
	public List<Askers> selectAskers(){
		return askersService.selectAll(null, null, null);
	}
	
	@RequestMapping("/getAllotAskers")
	public boolean getAllotAskers(String ids,String askerid,String zixunname) {
		String[] id = ids.split(",");
		Students students = new Students();
		int flag = 0;
		for (int i = 0; i < id.length; i++) {
			students.setId(id[i]);
			students.setAskerid(askerid);
			students.setZixunname(zixunname);
			flag = studentsService.update(students);
		}
		return flag>0?true:false;
	}
	
	
	
	
}
